package com.springboot.application.advices;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.springboot.application.enums.ResultCodeEnum;
import com.springboot.application.exceptions.ApiException;
import com.springboot.application.response.ResultResponse;
import lombok.SneakyThrows;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

@RestControllerAdvice(basePackages = {"com.springboot.application.controller"})
public class ControllerResponseAdvice implements ResponseBodyAdvice<Object> {
    @Override
    public boolean supports(MethodParameter returnType, Class<? extends HttpMessageConverter<?>> converterType) {
        //response 是ResultResponse 类型 或者注释了NotControllerResponseAdvice都不进行包装
        return !returnType.getParameterType().isAssignableFrom(ResultResponse.class);
    }

    @Override
    public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType, Class<? extends HttpMessageConverter<?>> selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
        //String 类型不能直接包装
        if (returnType.getGenericParameterType().equals(String.class)) {
            ObjectMapper objectMapper = new ObjectMapper();
            try {
                // 将数据包装在ResultResponse里后转换为json串返回
                return objectMapper.writeValueAsString(new ResultResponse(body));
            } catch (JsonProcessingException e) {
                throw new ApiException(ResultCodeEnum.RESPONSE_PACK_ERROR, e.getMessage());
            }
        }
        return new ResultResponse(body);
    }
}
